﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GiMess.Net;
using System.IO;
using System.Threading;
using GiMessCommons;

namespace GiMess
{
    public class GiNetClient
    {
        NetClient       netClient;
        NetMsgHandler   msgHandler;
        BinaryWriter    binWriter;

        public static GiNetClient Instance { get; private set; }

        public GiNetClient()
        {
            netClient  = new NetClient();
            msgHandler = new NetMsgHandler();         

            netClient.NewNetMsg += msgHandler.HandleMsg;

            Instance = this;

            //netClient.Connect("127.0.0.1", 1234);

            //ThreadStart clientThreadStart = netClient.Listen;
            //clientThread = new Thread(clientThreadStart);
            //clientThread.Name = "NetWorker";
            //clientThread.Start();

            //netClient.SendNetMsg(new Net.NetMsg(NetServices.SEND_MESSAGE, "message"));
            //Thread.Sleep(100);
            //SendIM("dburner", "mesajÀ€abcdÀ€mesaj");
        }

        public void Connect()
        {
            netClient.Connect(NetConsants.ConnectionIP, NetConsants.ConnectionPort);
            Thread.Sleep(100);
        }

        public void Disconnect()
        {
            if (netClient.WorkerThread != null)
                netClient.WorkerThread.Abort();
            netClient.Disconnect();
        }


        public void Login(string userName, string userPassword)
        {
            Connect();
            userPassword = NetUtils.EncodePassword(userPassword);

            DataFieldsWriter data = new DataFieldsWriter();
            data.WriteField(Field.AuthUserName, userName);
            data.WriteField(Field.AuthUserPassword, userPassword);

            netClient.SendNetMsg(NetServices.Auth, data.GetString());
            //netClient.SendNetMsg(NetServices.Auth, "abcde");
        }

        public void SendListRequest()
        {
            netClient.SendNetMsg(NetServices.ListRequest, "");
        }

        public void SendIM(string toUserName, string text)
        {
            //se inlocuieste delimitatorul cu codul lui din html
            text = text.Replace(NetConsants.FieldsDelimiter, NetConsants.FieldsDelimiterReplace);

            DataFieldsWriter data = new DataFieldsWriter();
            data.WriteField(Field.MessageUserOrigin, AuthInfo.UserName);
            data.WriteField(Field.MessageUserDest,   toUserName);
            data.WriteField(Field.MessageText,       text);

            netClient.SendNetMsg(NetServices.SendMessage, data.GetString());
        }
    }
}
